package gui.chatarea;

import gui.userslist.UserTargetedListener;

import java.awt.Dimension;
import java.util.Map;

import javax.swing.JEditorPane;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.html.HTMLEditorKit;

import controller.MessageController;

public class ChatArea extends JScrollPane {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private HTMLChatDocument doc = null ;

	public ChatArea (UserTargetedListener usl, MessageController msgCtrl,
			Map <String, String> userColors) {
		super (new JEditorPane()) ;
		final JEditorPane editor = (JEditorPane) getViewport().getView() ;
		editor.setOpaque(true) ;
		HTMLEditorKit kit = new HTMLEditorKit () ;
		editor.setEditorKit(kit) ;
		kit.setStyleSheet(new ChatStyleSheet()) ;
		this.doc = new HTMLChatDocument(kit.getStyleSheet(), userColors) ;
		editor.setDocument(this.doc) ;
		editor.setEditable(false) ;
		editor.addHyperlinkListener(new ChatHyperLinkListener(getParent(), usl, msgCtrl)) ;
		editor.getDocument().addDocumentListener(new DocumentListener() {
						
			@Override
			public void removeUpdate(DocumentEvent e) {}
			
			@Override
			public void insertUpdate(DocumentEvent e) {
				JScrollBar jsb = getVerticalScrollBar() ;
				/* Value = Position du haut de la barre,
				 * VisibleAmount = Hauteur de la barre
				 * Maximum = Hauteur du scroll
				 */
				if ((jsb.getValue() + jsb.getVisibleAmount()) == jsb.getMaximum()) {
					editor.setCaretPosition(e.getDocument().getLength()) ;
				}
			}
			
			@Override
			public void changedUpdate(DocumentEvent e) {}
		}) ;
		setMinimumSize(new Dimension(200, 200)) ;
	}
	
	public HTMLChatDocument getDocument () {
		return this.doc ;
	}
	
}
